package com.hunan.api.catv.utils;

import com.google.gson.JsonObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ExportExcel {

    public static Logger log = LoggerFactory.getLogger(ExportExcel.class);

    private String path;

    private String title;

    private String[] rowName;

    private List<Object[]> dataList = new ArrayList<Object[]>();

    private Integer task;

    private JsonObject ossConf;

    public ExportExcel(String title, String[] rowName, List<Object[]> dataList, Integer task, String path, JsonObject ossConf) {
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.task = task;
        this.path = path;
        this.ossConf = ossConf;
    }

    public String export() {
        HSSFWorkbook workbook = new HSSFWorkbook();
        try {
            HSSFSheet sheet = workbook.createSheet(title);
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);
            rowm.setHeight((short) (25 * 30));
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
            HSSFCellStyle style = this.getStyle(workbook);
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(title);
            int columnNum = rowName.length;
            HSSFRow rowRowName = sheet.createRow(2);
            rowRowName.setHeight((short) (25 * 30));
            for (int n = 0; n < columnNum; n++) {
                HSSFCell cellRowName = rowRowName.createCell(n);
                cellRowName.setCellType(CellType.STRING);
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);
                cellRowName.setCellStyle(columnTopStyle);
            }
            for (int i = 0; i < dataList.size(); i++) {
                Object[] obj = dataList.get(i);
                HSSFRow row = sheet.createRow(i + 3);
                row.setHeight((short) (25 * 20));
                for (int j = 0; j < obj.length; j++) {
                    HSSFCell cell = null;
                    if (j == 0) {
                        cell = row.createCell(j, CellType.NUMERIC);
                        cell.setCellValue(i + 1);
                    } else {
                        cell = row.createCell(j, CellType.STRING);
                        if (!StringUtils.isEmpty(obj[j])) {
                            cell.setCellValue(obj[j].toString());
                        } else {
                            cell.setCellValue("");
                        }
                    }
                    cell.setCellStyle(style);
                }
            }
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (!StringUtils.isEmpty(currentRow.getCell(colNum))) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellType() == CellType.STRING) {
                            if (!StringUtils.isEmpty(currentCell.getStringCellValue())) {
                                int length = currentCell.getStringCellValue().getBytes().length;
                                if (columnWidth < length) {
                                    columnWidth = length;
                                }
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            }
            if (!ObjectUtils.isEmpty(workbook)) {
                String diskPath = getFile();
                try {
                    File file = new File(diskPath + title);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
                    workbook.write(stream);
                    stream.flush();
                    stream.close();
                    String domainPath = upload(1, file);
                    file.delete();
                    if (!ObjectUtils.isEmpty(domainPath)) {
                        return domainPath;
                    }
                } catch (Exception e) {
                    log.error("error:{}", e);
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e);
        }
        return null;
    }

    /**
     * 列表数据格式
     *
     * @param workbook
     * @return
     */
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("Courier New");
        HSSFCellStyle style = workbook.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        style.setFont(font);
        style.setWrapText(false);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return style;
    }

    /**
     * 单元格样式
     */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        //font.setFontHeightInPoints((short)10);
        //字体加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("黑体");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    public String getFile() {
        String currentDay = DateTime.now().toString("yyyyMMdd");
        StringBuilder diskPathBuilder = new StringBuilder();
        diskPathBuilder.append(path);
        diskPathBuilder.append("/");
        diskPathBuilder.append("/");
        diskPathBuilder.append(currentDay);
        diskPathBuilder.append("/");
        String diskPath = diskPathBuilder.toString();
        File uploadPathDir = new File(diskPath);
        if (!uploadPathDir.exists()) {
            uploadPathDir.mkdirs();
        }
        return diskPath;
    }

    public String upload(Integer fileType, File file) {
        if (!ObjectUtils.isEmpty(ossConf)) {
            String secretId = ossConf.get("secretId").getAsString();
            String secretKey = ossConf.get("secretKey").getAsString();
            String region = ossConf.get("region").getAsString();
            String bucketName = ossConf.get("bucketName").getAsString();
            String domain = ossConf.get("domain").getAsString();
            String fileName = file.getName();
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String currentDay = DateTime.now().toString("yyyyMMdd");
            StringBuilder keyBuilder = new StringBuilder();
            keyBuilder.append(fileType == 1 ? "excel/" : "");
            keyBuilder.append(currentDay);
            keyBuilder.append("/");
            keyBuilder.append(fileName);
            StringBuilder domainPathBuilder = new StringBuilder();
            domainPathBuilder.append(domain);
            domainPathBuilder.append("/");
            domainPathBuilder.append(keyBuilder);
            String domainPath = domainPathBuilder.toString();
            String eTag = upload(file, secretId, secretKey, region, bucketName, keyBuilder.toString(), fileSuffix);
            if (!ObjectUtils.isEmpty(eTag)) {
                JsonObject result = new JsonObject();
                result.addProperty("size", FileUtils.convertFileSize(file.length()));
                result.addProperty("realSize", file.length());
                result.addProperty("fileId", eTag);
                result.addProperty("url", domainPath);
                return domainPath;
            }
        }
        return null;
    }

    public String upload(File file, String secretId, String secretKey, String region, String bucketName, String key, String fileSuffix) {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosclient = new COSClient(cred, clientConfig);

        try {
            InputStream inputStream = new FileInputStream(file);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.length());
            if ("xls".equals(fileSuffix.toLowerCase()) || "xls".equals(fileSuffix.toLowerCase())) {
                objectMetadata.setContentType("application/x-xls");
            }
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            return putObjectResult.getETag();
        } catch (CosServiceException e) {
            log.error("[Cos-Error:" + e.toString() + "]");
        } catch (CosClientException e) {
            log.error("[Cos-Error:" + e.toString() + "]");
        } catch (IOException e) {
            log.error("[Cos-Error:" + e.toString() + "]");
        } finally {
            cosclient.shutdown();
        }
        return fileSuffix;
    }
}
